package com.fish.anne.webapp.action;

import com.opensymphony.xwork2.Preparable;
import com.fish.anne.service.MemberCouponManager;
import com.fish.anne.model.MemberCoupon;
import com.fish.anne.webapp.action.BaseAction;

import java.util.List;

public class MemberCouponAction extends BaseAction implements Preparable {
    private MemberCouponManager memberCouponManager;
    private List memberCoupons;
    private MemberCoupon memberCoupon;
    private Long  memberCouponId;

    public void setMemberCouponManager(MemberCouponManager memberCouponManager) {
        this.memberCouponManager = memberCouponManager;
    }

    public List getMemberCoupons() {
        return memberCoupons;
    }

    /**
     * Grab the entity from the database before populating with request parameters
     */
    public void prepare() {
        if (getRequest().getMethod().equalsIgnoreCase("post")) {
            // prevent failures on new
            String memberCouponId = getRequest().getParameter("memberCoupon.memberCouponId");
            if (memberCouponId != null && !memberCouponId.equals("")) {
                memberCoupon = memberCouponManager.get(new Long(memberCouponId));
            }
        }
    }

    public String list() {
        memberCoupons = memberCouponManager.getAll();
        return SUCCESS;
    }

    public void setMemberCouponId(Long  memberCouponId) {
        this. memberCouponId =  memberCouponId;
    }

    public MemberCoupon getMemberCoupon() {
        return memberCoupon;
    }

    public void setMemberCoupon(MemberCoupon memberCoupon) {
        this.memberCoupon = memberCoupon;
    }

    public String delete() {
        memberCouponManager.remove(memberCoupon.getMemberCouponId());
        saveMessage(getText("memberCoupon.deleted"));

        return SUCCESS;
    }

    public String edit() {
        if (memberCouponId != null) {
            memberCoupon = memberCouponManager.get(memberCouponId);
        } else {
            memberCoupon = new MemberCoupon();
        }

        return SUCCESS;
    }

    public String save() throws Exception {
        if (cancel != null) {
            return "cancel";
        }

        if (delete != null) {
            return delete();
        }

        boolean isNew = (memberCoupon.getMemberCouponId() == null);

        memberCouponManager.save(memberCoupon);

        String key = (isNew) ? "memberCoupon.added" : "memberCoupon.updated";
        saveMessage(getText(key));

        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }
    }
}